/* eslint-disable no-unused-vars */
import React, { useEffect, useState } from 'react'
import { Dropdown, Space, Modal, Form, Input, Button } from 'antd'
import {
  EllipsisOutlined,
  CopyOutlined,
  StarOutlined,
  CloseOutlined,
  ExportOutlined,
  EditOutlined,
  SwapOutlined
} from '@ant-design/icons'
import '../assets/wsl.css'
import GlobalContext from './GlobalContext.jsx'

const { openBrowser } = window.api.common
const {
  showReason,
  startOrStop,
  queryBtns,
  changeQueryStatus,
  openFileDialog,
  formRef,
  shutdownAll,
  wslList,
  vars,
  renameFormRef,
  copyFormRef,
  initDatas,
  getDatasByTimer,
  handleNameValidate,
  handleAfterClose,
  handleImportModalOk,
  handleImportModalCancel,
  handleReNameModalOk,
  handleReNameModalCancel,
  handleCopyModalOk,
  handleCopyModalCancel,
  clickMenuItem
} = window.api.wsl

function Wsl() {
  const [datas, setDatas] = useState([])
  const [curPage, setCurPage] = useState(1)
  const [formLayout, setFormLayout] = useState('vertical')
  const [importOpen, setImportOpen] = useState(false)
  const [reNameOpen, setReNameOpen] = useState(false)
  const [copyOpen, setCopyOpen] = useState(false)

  // 下拉菜单项
  const items = (item) => {
    const menuItems = [
      { key: '6', label: vars.ctx.t('copy'), icon: <CopyOutlined /> },
      { key: '2', label: vars.ctx.t('export'), icon: <ExportOutlined /> },
      { key: '4', label: vars.ctx.t('rename'), icon: <EditOutlined /> },
      { type: 'divider' },
      { key: '3', label: vars.ctx.t('delete'), icon: <CloseOutlined /> }
    ]
    let migIndex = 2
    if (!item.default) {
      menuItems.splice(0, 0, {
        key: '1',
        label: vars.ctx.t('default'),
        icon: <StarOutlined />,
        handler: 'setDefault'
      })
      migIndex = 3
    }
    if (
      !vars.migratePth ||
      (vars.migratePth && vars.migrated.length === 0) ||
      (vars.migrated.length > 0 && vars.migrated.indexOf(item.name.toLowerCase()) < 0)
    ) {
      menuItems.splice(migIndex, 0, {
        key: '5',
        label: vars.ctx.t('migrate'),
        icon: <SwapOutlined />
      })
      item.migrated = false
    } else {
      item.migrated = true
    }
    return menuItems
  }

  useEffect(() => initDatas(setDatas), [])
  useEffect(() => getDatasByTimer(setDatas), [])

  return (
    <GlobalContext.Consumer>
      {(context) => {
        vars.ctx = context
        const t = context.t
        return (
          <div className="wsl">
            <div className="wsl-tools">
              <div className="wsl-tools-functions">
                <span style={{ display: 'none' }} className="wsl-tools-item">
                  安装
                </span>
                <span className="wsl-tools-item" onClick={() => setImportOpen(!importOpen)}>
                  {t('import')}
                </span>
                <span className="wsl-tools-item" onClick={() => shutdownAll()}>
                  {t('shutdownAll')}
                </span>
              </div>
              <div className="wsl-tools-queries">
                <span
                  ref={queryBtns[0]}
                  className="wsl-tools-item wsl-tools-item-active"
                  onClick={() => {
                    vars.qryIndex = 0
                    setCurPage(1)
                    changeQueryStatus(queryBtns[vars.qryIndex])
                    wslList(setDatas)
                  }}
                >
                  {context.t('all')}
                </span>
                <span
                  ref={queryBtns[1]}
                  className="wsl-tools-item"
                  onClick={() => {
                    vars.qryIndex = 1
                    setCurPage(1)
                    changeQueryStatus(queryBtns[vars.qryIndex])
                    wslList(setDatas)
                  }}
                >
                  {context.t('running')}
                </span>
              </div>
            </div>
            <div className="wsl-title">
              <div className="wsl-title-item">{context.t('titleName')}</div>
              <div className="wsl-title-item">{context.t('titleState')}</div>
              <div className="wsl-title-item">{context.t('titleVersion')}</div>
              <div className="wsl-title-item">{context.t('titleOpt')}</div>
            </div>
            <div>
              {datas.length > 0 &&
                datas[curPage - 1].map((item, index) => {
                  return (
                    <div className="wsl-list-row" key={index}>
                      <div className="wsl-list-item">{(item.default ? '* ' : '') + item.name}</div>
                      <div className="wsl-list-item">{item.state}</div>
                      <div className="wsl-list-item">{item.version}</div>
                      <div className="wsl-list-item">
                        {(item.state === 'Stopped' || item.state === 'Running') && (
                          <span
                            className="operation-item"
                            onClick={() =>
                              startOrStop(item, item.state === 'Stopped' ? 'start' : 'stop')
                            }
                          >
                            {item.state === 'Stopped' ? context.t('start') : context.t('shutdown')}
                          </span>
                        )}
                        <Dropdown
                          menu={{
                            items: items(item),
                            onClick: (key) => {
                              key.data = item
                              clickMenuItem(key, setReNameOpen, setCopyOpen)
                            }
                          }}
                          className="operation-item"
                        >
                          <a onClick={(e) => e.preventDefault()}>
                            <Space>
                              &nbsp;
                              <EllipsisOutlined />
                              &nbsp;
                            </Space>
                          </a>
                        </Dropdown>
                      </div>
                    </div>
                  )
                })}
              {datas.length === 0 && (
                <div
                  style={{
                    width: '100%',
                    textAlign: 'center',
                    padding: '30px'
                  }}
                >
                  <p style={{ marginBottom: '20px' }}>
                    {t('noData')}
                    {vars.showRson && vars.qryIndex === 0 && (
                      <>
                        <span
                          onClick={() => showReason()}
                          style={{
                            cursor: 'pointer',
                            color: 'yellow',
                            fontSize: '14px'
                          }}
                        >
                          {t('click4Reson')}
                        </span>
                        <div
                          style={{
                            marginTop: '20px'
                          }}
                        >
                          {t('detail')}
                          <span
                            style={{
                              cursor: 'pointer',
                              color: 'yellow'
                            }}
                            onClick={(e) => openBrowser(e, 'https://aka.ms/wslinstall')}
                          >
                            https://aka.ms/wslinstall
                          </span>
                          {t('period')}
                        </div>
                      </>
                    )}
                  </p>
                </div>
              )}
            </div>
            {datas.length > 1 && (
              <div className="list-page">
                {curPage === 1 && (
                  <div className="list-page-item list-page-item-notallowed">{t('prev')}</div>
                )}
                {curPage > 1 && (
                  <div className="list-page-item" onClick={() => setCurPage(curPage - 1)}>
                    {t('prev')}
                  </div>
                )}
                <div className="list-page-num">
                  {curPage} / {datas.length}
                </div>
                {curPage === datas.length && (
                  <div className="list-page-item list-page-item-notallowed">{t('next')}</div>
                )}
                {curPage < datas.length && (
                  <div className="list-page-item" onClick={() => setCurPage(curPage + 1)}>
                    {t('next')}
                  </div>
                )}
              </div>
            )}
            {/* 导入对话框 */}
            <Modal
              title={t('importTitle')}
              open={importOpen}
              onOk={handleImportModalOk.bind(this, setImportOpen)}
              onCancel={handleImportModalCancel.bind(this, setImportOpen)}
              okText={t('importText')}
              cancelText={context.t('cancelText')}
              afterClose={handleAfterClose}
            >
              <Form layout={formLayout} ref={formRef}>
                <Form.Item
                  label={t('importingFile')}
                  name={'pathField1'}
                  rules={[{ required: true }]}
                >
                  <Space.Compact style={{ width: '100%' }}>
                    <Form.Item
                      name={'pathField'}
                      style={{ width: '100%' }}
                      rules={[{ required: true, message: t('selectImpFile') }]}
                    >
                      <Input placeholder={t('selectImpFile')} disabled={true} />
                    </Form.Item>
                    <Button onClick={() => openFileDialog()}>{t('selectFile')}</Button>
                  </Space.Compact>
                </Form.Item>
                <Form.Item
                  name={'nameField'}
                  label={t('newName')}
                  rules={[
                    { required: true, message: t('newNameRequired') },
                    { validator: handleNameValidate }
                  ]}
                >
                  <Input placeholder={t('inputNewName')} />
                </Form.Item>
                <div></div>
              </Form>
            </Modal>
            {/* 重命名对话框 */}
            {/* {pattern: new RegExp(newNameReg, 'g'), message: '名称必须以字母开头，且只能包含大小写字母、数字、_和-'} */}
            <Modal
              title={t('reNameTitle')}
              open={reNameOpen}
              onOk={handleReNameModalOk.bind(this, setReNameOpen)}
              onCancel={handleReNameModalCancel.bind(this, setReNameOpen)}
              okText={t('okText')}
              cancelText={t('cancelText')}
            >
              <Form layout={formLayout} ref={renameFormRef}>
                <Form.Item
                  name={'newName'}
                  label={t('newName')}
                  rules={[
                    { required: true, message: t('newNameRequired') },
                    { max: 20, message: t('nameLenCheck') },
                    { validator: handleNameValidate }
                  ]}
                >
                  <Input placeholder={t('inputNewName')} />
                </Form.Item>
              </Form>
            </Modal>
            {/* 拷贝对话框 */}
            <Modal
              title={context.t('copy')}
              open={copyOpen}
              okText={t('okText')}
              cancelText={t('cancelText')}
              onOk={handleCopyModalOk.bind(this, setCopyOpen)}
              onCancel={handleCopyModalCancel.bind(this, setCopyOpen)}
            >
              <Form layout={formLayout} ref={copyFormRef}>
                <Form.Item
                  name={'copyName'}
                  label={t('newName')}
                  rules={[
                    { required: true, message: t('newNameRequired') },
                    { max: 20, message: '名称不能超过20个字符' },
                    { validator: handleNameValidate }
                  ]}
                >
                  <Input placeholder={t('inputNewName')} />
                </Form.Item>
              </Form>
            </Modal>
          </div>
        )
      }}
    </GlobalContext.Consumer>
  )
}

export default Wsl
